package com.yuantu.judiciary.serviceimpl;

import com.yuantu.judiciary.common.SysCode;
import com.yuantu.judiciary.exception.ServiceException;
import com.yuantu.judiciary.service.ISysFileService;
import com.yuantu.judiciary.utils.AssertUtil;
import com.yuantu.judiciary.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * 系统文件接口实现
 *
 * @author syw
 * @since 2023-07-18
 **/
@Service
@RequiredArgsConstructor
@Slf4j
public class SysFileServiceImpl implements ISysFileService {

    @Override
    public String fileUpload(MultipartFile file, String path) {
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(file), SysCode.FILE_EMPTY);
        //上传文件的大小, 单位为字节.
        long fileSize = file.getSize();
        if (fileSize > 500 * 1024 * 1024) {
            throw new ServiceException(SysCode.FILE_SIZE_TOO_BIG);
        }
        // 文件名
        String fileName = file.getOriginalFilename();
        AssertUtil.assertTrue(StringUtils.isNotEmpty(fileName), SysCode.FILE_NAME_EMPTY);
        try {
            // 后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            String rand = UUID.randomUUID().toString().replaceAll("-", "");
            // 新文件名
            fileName = rand + suffixName;
            File direction = new File(path);
            File savedFile = new File(direction, fileName);
            if (!savedFile.getParentFile().exists()) {
                savedFile.getParentFile().mkdirs();
            }
            FileUtils.copyInputStreamToFile(file.getInputStream(), savedFile);
            return path + "/" + fileName;
        } catch (Exception e) {
            log.error("上传文件失败", e);
            throw new ServiceException(SysCode.FILE_UPLOAD_FAIL);
        }
    }

    @Override
    public Boolean fileDownload(HttpServletResponse response, String url) {
        InputStream in = null;
        OutputStream out = null;
        try {
            //3.设置content-disposition响应头控制浏览器以下载的形式打开文件
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-disposition", "attachment;filename=" + java.net.URLEncoder.encode(url, "UTF-8"));
            //4.获取要下载的文件输入流
            in = Files.newInputStream(Paths.get(url));
            int len = 0;
            //5.创建数据缓冲区
            byte[] buffer = new byte[1024];
            //6.通过response对象获取OutputStream流
            out = response.getOutputStream();
            //7.将FileInputStream流写入到buffer缓冲区
            while ((len = in.read(buffer)) > 0) {
                //8.使用OutputStream将缓冲区的数据输出到客户端浏览器
                out.write(buffer, 0, len);
            }
            return true;
        } catch (Exception e) {
            log.error("下载文件失败");
            throw new ServiceException(SysCode.FILE_DOWNLOAD_FAIL);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {
                log.error("关闭文件流失败");
            }
        }
    }

    @Override
    public String downloadMapJson() {
        return FileUtil.getTemplateContent("files/default/mapData.json");
    }
}
